from rest_framework.viewsets import ModelViewSet
from app01.models import Book
from app01.ser import BookSerializer
from rest_framework.viewsets import ModelViewSet
from rest_framework.response import Response
from rest_framework.decorators import action  # 装饰器
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework import settings

from app01.models import Book
from app01.ser import BookSerializer
from app01.app_auth import MyAuthentication


# Create your views here.


class BookViewSet(ModelViewSet):

    authentication_classes = [MyAuthentication]
    queryset = Book.objects.all()
    serializer_class = BookSerializer

    @action(methods=['GET', 'post'], detail=True)  # detail True表示生成带pk的路由
    def get_1(self, request, pk):
        print(request.user.username)
        # book = self.get_queryset()[:1]  # 从0开始截取一条
        book = self.get_object()
        ser = self.get_serializer(instance=book)
        return Response(ser.data)


class TestView(APIView):
    def get(self, request):
        print(request.user.username)
        return Response({'msg': '测试'})


from app01 import models
import uuid
class LoginView(APIView):
    authentication_classes = []  # 禁用全局认证
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        user = models.User.objects.filter(username=username, password=password).first()
        if user:
            # 登录成功，生成一个随机字符串
            token = uuid.uuid4()
            # 存到UserToken表中
            models.UserToken.objects.update_or_create(defaults={'token': token}, user=user)  # 每次登陆都会记录一条, 不好
            # models.UserToken.objects.create(token=token, user=user)  # 每次登陆都会记录一条, 不好
            return Response({'status': 100, 'msg': '登录成功', 'token': token})
        else:
            return Response({'status': 101, 'msg': '用户名或密码错误'})